using MultiAgentsClient.Manager.DataModel;
using MultiAgentsClient.Service.SignalRService;
using MultiAgentsShared;
using static MultiAgentsClient.Service.SignalRService.SignalRClientServiceBase;
using ApiRequestType = MultiAgentsClient.Service.SignalRService.SignalRUserService.ApiRequestType;
using static MultiAgentsClient.Manager.LocalDataOperator;

namespace MultiAgentsClient.Manager;

public class AutoLoginManager(
    SignalRUserService signalRUserService,
    SystemConfigDataModel systemConfigDataModel,
    LocalDataOperator localDataOperator)
{
    private readonly SignalRUserService signalRUserService = signalRUserService;
    private readonly SystemConfigDataModel systemConfigDataModel = systemConfigDataModel;
    private readonly LocalDataOperator localDataOperator = localDataOperator;

    public async Task LoginAutoRequest()
    {
        Dictionary<string, string> sessionData = localDataOperator.GetLoginInformation();

        if (sessionData.Count == 0
            || !sessionData.TryGetValue(SessionData.UserName.ToString(), out var userName)
            || !sessionData.TryGetValue(SessionData.Password.ToString(), out var password)
            || !sessionData.TryGetValue(SessionData.ServerName.ToString(), out var serverName)
            || !sessionData.TryGetValue(SessionData.SessionId.ToString(), out var sessionId))
        {
            return;
        }

        EventBus eventBus = EventBus.Instance;
        eventBus.Publish(new ConnectServerCommand(serverName));

        systemConfigDataModel.sessionId = sessionId;

        await signalRUserService.SendSignalRRequest(ApiRequestType.AutoLoginApiRequest.ToString(), new Dictionary<string, object>()
        {
            { "sessionId", sessionId },
            { "userName", userName },
            { "userPasswordEncrypted", password },
        });
    }
}
